<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import {
  NSpace,
  NButton,
  type FormInst,
  NForm,
  NFormItem,
  NInput,
  NSelect,
  type FormRules,
  useMessage,
  NScrollbar,
  NSpin
} from 'naive-ui'
import { sendRequest } from '@/utils/api'
import FixedAction from '@/components/FixedAction.vue'
import { keysOf } from '@/utils/object'
import { useRoute } from 'vue-router'
import BasicInfo from '@/components/CollectProcess/BasicInfo.vue'
import useRouteReplace from '@/hooks/useRouteReplace'
const props = defineProps({
  id: { type: String, default: () => null },
  typeShow: { type: Number, default: () => 0 },
  code: { type: String, default: () => null },
  typeIn: { type: Number, default: () => null }
})
const route = useRoute()
const routeReplace = useRouteReplace(route.query.redirect as string)
console.log(route)
// const isDetail = route.path === '/collection/process/initCompilation/processDetail'
const array = props?.id?.split(',') || []
const message = useMessage()
const userFormRef = ref<FormInst | null>(null)
const loading = ref(false)
const form: any = reactive({
  id: array?.[0],
  password: array?.[0] ? null : 'Aa123456!',
  userStatus: 1,
  typeTree: null,
  typeTreeS: null,
  typeTreeT: null,
  time: null,
  name: null,
  repactName: null,
  collectName: null,
  phone: null,
  person: null,
  dujiaoName: null,
  Uptime: null,
  price: null,
  author: null,
  number1: null,
  yesNO: null,
  yinciTime: null,
  remack: null,
  ziicaCode: null,
  serialNumber: null,
  position: null,
  itemsStaging: {
    assetCode: null,
    firstLevelCode: null,
    threeLevelCode: null,
    secondLevelCode: null,
    fifthLevelCode: null,
    fourthLevelCode: null,
    serialNumber: null
  }
})
const optionInPosition0 = ref([])
const optionInPosition1 = ref([])
const optionInPosition2 = ref([])
const optionInPosition3 = ref([])
const optionInPosition4 = ref([])
const optionInPosition5 = ref([])
const formRules: FormRules = {
  itemsStaging: {
    assetCode: {
      required: false,
      trigger: ['blur', 'input'],
      validator: () => {
        if (!form.itemsStaging.assetCode)
          if (!Number.isFinite(Number(form.itemsStaging.assetCode))) {
            return new Error('馆藏码必须为数字')
          }
        if (form.itemsStaging.assetCode.toString().length > 18) {
          return new Error('馆藏码最多18位')
        }
        return true
        // if (!/^[0-9]{1,18}$/g.test(form.itemsStaging.assetCode)) return new Error('馆藏码最多18位')
      }
    },
    // fifthLevelCode: {
    //   required: optionInPosition4.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    // sixthLevelCode: {
    //   required: optionInPosition5.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    firstLevelCode: {
      // required: optionInPosition0.value.length > 0 ? true : false,
      required: true,
      trigger: ['blur', 'change'],
      type: 'any',
      message: '不能为空'
    }
    // secondLevelCode: {
    //   required: optionInPosition1.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    // threeLevelCode: {
    //   required: optionInPosition2.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // },
    // fourthLevelCode: {
    //   required: optionInPosition3.value.length > 0 ? true : false,
    //   trigger: ['blur', 'change'],
    //   type: 'any',
    //   message: '不能为空'
    // }
  }
}

const handleUpdateAssetCode = (e: any) => {
  if (e && e.length > 18) {
    form.itemsStaging.assetCode = e.slice(0, 18)
    return message.error('馆藏码最多18位')
  }
  form.itemsStaging.assetCode = e
}

const getFirstFn = async (id: any, refValue: any) => {
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api: 'listOptionsByParentId',
    override: {
      params: {
        parentId: id
      }
    }
  })
  if (error) return message.error(error.message)
  refValue.value = res?.data || []
}

const changeOptionFn = (e: any, type: any) => {
  switch (type) {
    case 1: {
      form.itemsStaging.secondLevelCode = null
      form.itemsStaging.threeLevelCode = null
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition1)
      break
    }
    case 2: {
      form.itemsStaging.threeLevelCode = null
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition2)
      break
    }
    case 3: {
      form.itemsStaging.fourthLevelCode = null
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition3)
      break
    }
    case 4: {
      form.itemsStaging.fifthLevelCode = null
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition4)
      break
    }
    case 5: {
      form.itemsStaging.sixthLevelCode = null
      getFirstFn(e, optionInPosition5)
      break
    }
  }
}

const submit = async () => {
  const validate = await Promise.all([
    // 暂时未使用
    // new Promise((resolve, reject) => {
    //   baseFormRef.value?.validate((error) => {
    //     if (error) return reject(error)
    //     resolve(true)
    //   })
    // }),
    new Promise((resolve, reject) => {
      userFormRef.value?.validate((error) => {
        if (error) return reject(error)
        resolve(true)
      })
    })
  ])

  if (!validate.every(Boolean)) return

  loading.value = true
  const [error, res] = await sendRequest({
    module: 'collectProcess',
    api:
      props?.typeIn == 1 || props?.typeIn == 2 ? 'updateStorage' : 'collectingItemsStagingUpdate',
    override: {
      data:
        props?.typeIn == 1 || props?.typeIn == 2
          ? {
              id: form.id,
              ...form.itemsStaging,
              storageType: props?.typeIn
            }
          : {
              id: form.id,

              ...form.itemsStaging
            }
    }
  })
  loading.value = false

  if (error) return message.error(error.message)
  if (res.code !== 0) return message.error(res.msg)
  message.success(res.msg)
  // goBack()
  routeReplace()
}
// 返回
const goBack = () => {
  // history.back()
  routeReplace()
}
const spinShow = ref(false)
const findDetail = async () => {
  spinShow.value = true
  sendRequest({
    module: 'collectProcess',
    api: 'collectingItemsInfo',
    uri: {
      id: props.id
    }
  }).then(async ([err, res]) => {
    if (err) return
    await getFirstFn(0, optionInPosition0)
    await getFirstFn(res.data?.itemsStaging?.firstLevelCode, optionInPosition1)
    await getFirstFn(res.data?.itemsStaging?.secondLevelCode, optionInPosition2)
    await getFirstFn(res.data?.itemsStaging?.threeLevelCode, optionInPosition3)
    await getFirstFn(res.data?.itemsStaging?.fourthLevelCode, optionInPosition4)
    await getFirstFn(res.data?.itemsStaging?.fifthLevelCode, optionInPosition5)
    spinShow.value = false
    keysOf(res.data).forEach((e) => {
      form[e] = res.data[e] as never
    })

    // res.data.itemTypeCode && getCodeFn(res.data.itemTypeCode, res.data.itemName)
    // form.itemsStaging.assetCode =
    //   res.data?.itemsStaging?.assetCode || res.data?.itemsStaging?.assetCode == 0
    //     ? res.data?.itemsStaging?.assetCode
    //     : null
    // form.itemsStaging.firstLevelCode = res.data?.itemsStaging?.firstLevelCode
    // form.itemsStaging.secondLevelCode = res.data?.itemsStaging?.secondLevelCode
    // form.itemsStaging.threeLevelCode = res.data?.itemsStaging?.threeLevelCode
    // form.itemsStaging.fourthLevelCode = res.data?.itemsStaging?.fourthLevelCode
    // form.itemsStaging.fifthLevelCode = res.data?.itemsStaging?.fifthLevelCode
    // form.itemsStaging.sixthLevelCode = res.data?.itemsStaging?.sixthLevelCode
  })
}

watch(
  () => props.id,
  () => {
    if (route.name == 'updateInitCompilation' || route.name == 'detailInitCompilation') {
      findDetail()
    }
  },
  { deep: true, immediate: true }
)
onMounted(async () => {
  // 修改回显
  if (props.id) {
    findDetail()
  }
})
</script>

<template>
  <DetailFormProvider>
  <div class="main">
    <div class="form_content">
      <NScrollbar>
        <NSpin :show="spinShow">
          <!-- <div class="topTitle">基本信息</div> -->
          <div class="content">
            <BasicInfo
              :id="props.id"
              :type-show="props.typeShow"
              :code="props.code"
            ></BasicInfo>
            <div class="topTitle">入库</div>
            <!-- 可能有问题<:disabled="props?.typeShow == 1 || props.typeIn == 2"> -->
            <DetailFormProvider :disabled="$props.typeShow != 1">
              <NForm
                :model="form"
                :rules="formRules"
                ref="userFormRef"
                label-placement="left"
                require-mark-placement="left"
                label-width="140rem"
              >
                <div style="display: grid; grid-template-columns: repeat(2, 1fr); gap: 0 30px">
                  <NFormItem
                    label="馆藏码："
                    path="itemsStaging.assetCode"
                  >
                    <NInput
                      :value="form.itemsStaging.assetCode"
                      @update:value="handleUpdateAssetCode"
                      class="inputWH"
                      :show-button="false"
                      :disabled="props?.typeShow == 1 || props.typeIn == 2"
                    />
                  </NFormItem>
                  <NFormItem
                    label="流水号："
                    path="itemsStaging.serialNumber"
                  >
                    <NInput
                      v-model:value="form.itemsStaging.serialNumber"
                      class="inputWH"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                </div>
                <NSpace>
                  <NFormItem
                    label="入库位置："
                    path="itemsStaging.firstLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.firstLevelCode"
                      placeholder="位置1"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition0"
                      @update-value="(e) => changeOptionFn(e, 1)"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.secondLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.secondLevelCode"
                      placeholder="位置2"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition1"
                      @update-value="(e) => changeOptionFn(e, 2)"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.threeLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.threeLevelCode"
                      placeholder="位置3"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition2"
                      @update-value="(e) => changeOptionFn(e, 3)"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.fourthLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.fourthLevelCode"
                      placeholder="位置4"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition3"
                      @update-value="(e) => changeOptionFn(e, 4)"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.fifthLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.fifthLevelCode"
                      placeholder="位置5"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition4"
                      @update-value="(e) => changeOptionFn(e, 5)"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                  <NFormItem
                    label=""
                    path="itemsStaging.sixthLevelCode"
                  >
                    <NSelect
                      v-model:value="form.itemsStaging.sixthLevelCode"
                      placeholder="位置6"
                      class="inputWHmin"
                      filterable
                      clearable
                      :options="optionInPosition4"
                      @update-value="(e) => changeOptionFn(e, 6)"
                      :disabled="props?.typeShow == 1"
                    />
                  </NFormItem>
                </NSpace>
              </NForm>
            </DetailFormProvider>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
</DetailFormProvider>
  <FixedAction>
    <NSpace justify="center">
      <NButton
        style="width: 78px"
        ghost
        @click="goBack"
      >
        {{ props?.typeShow == 0 ? '取消' : '关闭' }}
      </NButton>
      <NButton
        type="primary"
        style="width: 78px"
        @click="submit"
        :loading="loading"
        v-if="props?.typeShow == 0"
      >
        确定
      </NButton>
    </NSpace>
  </FixedAction>
</template>
<style scoped lang="scss">
@mixin CommonFont {
  font-size: 18rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: #333333;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .form_content {
    width: 100%;
    height: 100%;
    padding: 20rem 20rem 0;

    .topTitle {
      font-size: 22px;
      font-family: PingFangSC, PingFang SC;
      font-weight: 500;
      color: #5fb17f;
      margin-bottom: 10rem;
    }

    .inputWH {
      flex: 1;
    }

    .inputWHmin {
      width: 150rem;
    }

    .content {
      display: flex;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 18rem 33rem 120rem;
      overflow-y: scroll;
      background-color: #ebeceb;
      @include CommonFont;
    }
  }
}

// .ac-card {
//     padding: 20rem;
//     background-color: #e1e1e1;
//   }

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
